﻿using System;
using System.Configuration;

namespace YanZhiwei.DotNet2.Utilities.Common
{
    /// <summary>
    ///App.config 帮助类
    /// </summary>
    public class ConfigHelper
    {
        #region AppSetting根据KEY获取对应的值
        /// <summary>
        /// AppSetting根据KEY获取对应的值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>值</returns>
        public static string GetAppSettingsValue(string key)
        {
            ConfigurationManager.RefreshSection("appSettings");
            return ConfigurationManager.AppSettings[key] ?? string.Empty;
        }
        #endregion 
        #region 修改AppSettings键值，若键不存在，则添加键值
        /// <summary>
        /// 修改AppSettings键值，若键不存在，则添加键值
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <returns>是否修改成功</returns>
        public static bool UpdateAppSettings(string key, string value)
        {
            var _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (!_config.HasFile)
            {
                throw new ArgumentException("程序配置文件缺失！");
            }
            KeyValueConfigurationElement _key = _config.AppSettings.Settings[key];
            if (_key == null)
                _config.AppSettings.Settings.Add(key, value);
            else
                _config.AppSettings.Settings[key].Value = value;
            _config.Save(ConfigurationSaveMode.Modified);
            return true;
        }
        #endregion 
    }
}
